# This files contains your custom actions which can be used to run
# custom Python code.
#
# See this guide on how to implement these action:
# https://rasa.com/docs/rasa/custom-actions
import csv
from typing import Any, Dict, List, Text

from rasa_sdk import Action, Tracker
from rasa_sdk.executor import CollectingDispatcher

data_list = []
# Title	Name	Review Date	Airline	Verified	Reviews	Type of Traveller	Month Flown	Route	Class	Seat Comfort	Staff Service	Food & Beverages	Inflight Entertainment	Value For Money	Overall Rating	Recommended	from				to	via
title_list = []


# amenities_Dry cleaning    amenities_DVD / CD player    amenities_Electric blanket    amenities_Electric kettle    amenities_Electric vehicle charging station    amenities_Entertainment staff    amenities_Evening entertainment    amenities_Executive lounge access    amenities_Express check- in / check-out    amenities_Extra long beds    amenities_Facial treatments    amenities_Family rooms    amenities_Fax / photocopying    amenities_Fence around pool    amenities_Fireplace    amenities_First aid kit    amenities_Fishing    amenities_Fitness / spa locker rooms    amenities_Fitness Center with Gym / Workout Room    amenities_Fitness classes    amenities_Flatscreen TV    amenities_Foot bath    amenities_Foot massage    amenities_Free airport transportation    amenities_Free breakfast    amenities_Free High Speed Internet (WiFi)    amenities_Free internet    amenities_Free parking    amenities_Free private parking nearby    amenities_Free public parking nearby    amenities_Free shuttle or taxi services    amenities_Free wifi in the business center    amenities_Free wired internet in the business center    amenities_Full body massage    amenities_Game room    amenities_Gift shop    amenities_Golf course    amenities_Hair dryer    amenities_Hammam    amenities_Hand massage    amenities_Happy hour    amenities_Head massage    amenities_Heated pool    amenities_Highchairs available    amenities_Hiking    amenities_Horseback riding    amenities_Hot tub    amenities_hotel_amenity_free_breakfast    amenities_hotel_amenity_free_internet    amenities_hotel_amenity_internet    amenities_hotel_amenity_wifi    amenities_Housekeeping    amenities_Indoor play area for children    amenities_Indoor pool    amenities_Interconnected rooms available    amenities_Internet    amenities_iPod docking station    amenities_Iron    amenities_Ironing service    amenities_Karaoke    amenities_Kid-friendly buffet    amenities_Kids' meals	amenities_Kids' outdoor play equipment    amenities_Kids club    amenities_Kids pool    amenities_Kids stay free    amenities_Kitchenette    amenities_Kitchenware    amenities_Landmark view    amenities_Laptop safe    amenities_Laundry service    amenities_Makeup services    amenities_Manicure    amenities_Massage    amenities_Massage chair    amenities_Meeting rooms    amenities_Microwave    amenities_Mini golf    amenities_Minibar    amenities_Mosquito net    amenities_Neck massage    amenities_Newspaper    amenities_Nightclub / DJ    amenities_Non-smoking hotel    amenities_Non-smoking rooms    amenities_On-demand movies    amenities_Open-air bath    amenities_Outdoor dining area    amenities_Outdoor fireplace    amenities_Outdoor furniture    amenities_Outdoor pool    amenities_Oven    amenities_Paid internet    amenities_Paid private parking nearby    amenities_Paid private parking on-site    amenities_Paid public parking nearby    amenities_Paid public parking on-site    amenities_Paid wifi    amenities_Parking    amenities_Parking garage    amenities_Patio    amenities_Pedicure    amenities_Personal trainer    amenities_Pets Allowed ( Dog / Pet Friendly )    amenities_Photo copier / fax In business center    amenities_Picnic area    amenities_Plunge pool    amenities_Pool    amenities_Pool / beach towels    amenities_Pool with view    amenities_Poolside bar    amenities_Private balcony    amenities_Private bathrooms    amenities_Private check- in / check-out    amenities_Private pool    amenities_Public wifi    amenities_Radio    amenities_Refrigerator    amenities_Restaurant    amenities_Rooftop bar    amenities_Rooftop pool    amenities_Rooftop terrace    amenities_Room service    amenities_Safe    amenities_Salon    amenities_Saltwater pool    amenities_Sauna    amenities_Seating area    amenities_Secured parking    amenities_Self-serve laundry    amenities_Separate dining area    amenities_Separate living room    amenities_Shallow end in pool    amenities_Shared bathroom    amenities_Shared kitchen    amenities_Shared lounge / TV area    amenities_Shoeshine    amenities_Shops    amenities_Shuttle bus service    amenities_Smoking rooms available    amenities_Snack bar    amenities_Sofa    amenities_Sofa bed    amenities_Solarium    amenities_Soundproof rooms    amenities_Spa    amenities_Special diet menus    amenities_Steam room    amenities_Stovetop    amenities_Street parking    amenities_Strollers    amenities_Suites    amenities_Sun deck    amenities_Sun loungers / beach chairs    amenities_Sun terrace    amenities_Sun umbrellas    amenities_Swimup bar    amenities_Table tennis    amenities_Taxi service    amenities_Telephone    amenities_Tennis court    amenities_Tennis court offsite    amenities_Tile / marble floor    amenities_Umbrella    amenities_Valet parking    amenities_Vending machine    amenities_Video game console    amenities_VIP room facilities    amenities_Wake-up service / alarm clock    amenities_Walk- in shower    amenities_Walking tours    amenities_Wardrobe / closet    amenities_Washing machine    amenities_Water park    amenities_Water park offsite    amenities_Waterslide    amenities_Waxing services    amenities_Whirlpool bathtub    amenities_Wifi    amenities_Wine / champagne    amenities_Yoga classes

def load_csv():
    print("action_query_hotel init -load_csv")
    with open('csv/hotel2.csv', encoding='ISO-8859-1') as f:
        read_data = csv.reader(f)
        is_first_row = True
        for row in read_data:
            if is_first_row:
                print("skip first row")
                global title_list
                title_list = row
                is_first_row = False
                continue
            data_list.append(row)


load_csv()


def find_match_item(budget, amenity_list):
    clean_title_list = []
    for title in title_list:
        title = title.replace(" ", "")
        title = title.lower()
        clean_title_list.append(title)

    match_item = []
    for item in data_list:
        # item_price_min = int(item[4])/100
        price_max = item[5]
        if price_max == 'NA':
            continue
        item_price_max = int(price_max) / 100

        if item_price_max > int(budget):
            continue

        match = True
        for amenity in amenity_list:
            clean_amenity_str = "amenities_" + amenity.lower().replace(" ", "")
            if clean_amenity_str not in clean_title_list:
                match = False
                continue
            index = clean_title_list.index(clean_amenity_str)
            # 0/1 amenity of item
            if str(item[index]) != '1':
                match = False
                continue
        if match:
            match_item.append(item)

    return match_item


class ActionQueryHotel(Action):

    def name(self) -> Text:
        return "action_query_hotel"

    def run(self, dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
        print("do action  action_query_hotel")
        # extra slot
        budget = tracker.get_slot('hotel_budget')
        amenity_list = tracker.get_slot('hotel_amenities')
        print(f"action extra,hotel_budget={budget},hotel_amenities={amenity_list}")

        match_item_list = find_match_item(budget, amenity_list)
        # limit 5
        match_item_list = match_item_list[0:5]
        has_match_flight = False
        if match_item_list:
            amenity_append_str = ""
            for a in amenity_list:
                amenity_append_str+=f"{a} "
            msg = f"Here are the hotels within your budget of {budget} {amenity_append_str}. You can click the url to view more details and booking information. Do you need me to assist you with the booking?\n"
            for match_item in match_item_list:
                msg += f"name:{match_item[2]} score:{match_item[3]} min price:{match_item[4]} max price:{match_item[5]} url:{match_item[1]}\n"
            dispatcher.utter_message(msg)
            has_match_flight = True
        else:
            msg = f"I'm sorry, we don't have hotel within your budget of {budget} with [{amenity_list}]. Do you have any other hotel needs?"
            dispatcher.utter_message(msg)

        return []
        # return [SlotSet("has_match_flight", has_match_flight)]


if __name__ == '__main__':
    load_csv()
    amenity_list = ["Air conditioning"]
    match_item_list = find_match_item(500, amenity_list)
    match_item_list = match_item_list[0:5]
    for match_item in match_item_list:
        print(match_item[2])
